package com.shine.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.shine.app.AppManager;
import com.shine.app.BaseActivity;
import com.shine.app.R;
import com.shine.app.bean.UserBean;
import com.shine.app.bean.UserInfoBean;
import com.shine.app.bean.request.SignUpBean;
import com.shine.app.bean.responses.AuthenticateUserResponse;
import com.shine.app.commons.StringUtils;
import com.shine.app.commons.UIHelper;
import com.shine.app.inject.InjectView;
import com.shine.app.inject.Injector;

public class RegisterActivity extends BaseActivity implements OnClickListener {

	@InjectView(R.id.head_back)
	private ImageView head_backImageView;
	@InjectView(R.id.head_name)
	private TextView head_nameTextView;
	@InjectView(R.id.name)
	private EditText namEditText;
	@InjectView(R.id.last)
	private EditText lastEditText;
	@InjectView(R.id.password)
	private EditText passwordEditText;
	@InjectView(R.id.confirm)
	private EditText confirmEditText;
	@InjectView(R.id.email)
	private EditText emailEditText;
	@InjectView(R.id.phoneNumber)
	private EditText phoneNumberEditText;
	@InjectView(R.id.agree)
	private CheckBox agreeCheckBox;
	@InjectView(R.id.send)
	private CheckBox sendCheckBox;
	@InjectView(R.id.register)
	private Button registerButton;
	@InjectView(R.id.progressBar)
	private ProgressBar progressBar;

	Handler handler = new Handler() {
		public void handleMessage(Message message) {
			if (message.what == 1) {
				UserInfoBean userInfoBean = (UserInfoBean) message.obj;
				UserBean user = userInfoBean.getUser();
				if (user != null) {
					Intent intent = new Intent(RegisterActivity.this,
							RegisterSuccessActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					RegisterActivity.this.startActivity(intent);
					AppManager.getAppManager().finishActivity();
					appContext.saveLoginInfo(userInfoBean);
					overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
				}
			} else if (message.what == 0) {
				UIHelper.toastDialog(RegisterActivity.this,
						R.string.registerfail, R.string.msg_yes);
			} else if (message.what == -1) {
				Exception exception = (Exception) message.obj;
				UIHelper.toastDialogs(RegisterActivity.this,
						exception.getMessage(), R.string.msg_yes);
			}
			resetViewStatus(true);
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		Injector.get(this).inject();

		progressBar.setVisibility(View.GONE);
		registerButton.setOnClickListener(this);
		head_backImageView.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.head_back:
			AppManager.getAppManager().finishActivity();
			overridePendingTransition(R.anim.anim, R.anim.slide_out_down);
			break;

		case R.id.register:
			registerButton.startAnimation(buttonAnimations);
			inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
			String firstName = namEditText.getText().toString().trim();
			String lastName = lastEditText.getText().toString().trim();
			String passWord = passwordEditText.getText().toString().trim();
			String confirm = confirmEditText.getText().toString().trim();
			String email = emailEditText.getText().toString().trim();
			String phoneNumber = phoneNumberEditText.getText().toString()
					.trim();
			if (!agreeCheckBox.isChecked()) {
				UIHelper.toastDialog(this,
						R.string.msg_should_agree_to_terms_register,
						R.string.msg_yes);
				return;
			}
			if (!validation(firstName, lastName, passWord, confirm, email,
					phoneNumber)) {
				return;
			}
			SignUpBean bean = new SignUpBean(firstName, lastName, email,
					passWord, phoneNumber, "US");
			register(bean);
			break;
		default:
			break;
		}
	}

	private boolean validation(String name, String last, String password,
			String confirm, String email, String phoneNumber) {
		if (StringUtils.isEmpty(name)) {
			UIHelper.toastDialog(this, R.string.msg_first_field_empty,
					R.string.msg_yes);
			return false;
		}
		if (StringUtils.isEmpty(last)) {
			UIHelper.toastDialog(this, R.string.msg_last_field_empty,
					R.string.msg_yes);
			return false;
		}
		if (StringUtils.isEmpty(email)) {
			UIHelper.toastDialog(this, R.string.msg_email_field_empty,
					R.string.msg_yes);
			return false;
		}
		if (!StringUtils.isEmail(email)) {
			UIHelper.toastDialog(this, R.string.msg_invalid_email_format,
					R.string.msg_yes);
			return false;
		}
		if (StringUtils.isEmpty(password)) {
			UIHelper.toastDialog(this, R.string.msg_password_field_empty,
					R.string.msg_yes);
			return false;
		}
		if (!password.equals(confirm)) {
			UIHelper.toastDialog(this, R.string.msg_password_confirm_not_equal,
					R.string.msg_yes);
			return false;
		}
		if (StringUtils.isEmpty(phoneNumber)) {
			UIHelper.toastDialog(this, R.string.msg_phone_field_empty,
					R.string.msg_yes);
			return false;
		}
		return true;
	}

	private void register(final SignUpBean bean) {
		resetViewStatus(false);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					AuthenticateUserResponse response = appContext
							.register(bean);
					if (response == null || response.isHasError()) {
						message.what = 0;
						message.obj = response;
					} else {
						message.what = 1;
						UserInfoBean userInfoBean = new UserInfoBean();
						UserBean userBean = response.getData();
						userBean.setEmail(bean.getEmail());
						userInfoBean.setPassword(bean.getPassword());
						userInfoBean.setUser(userBean);
						message.obj = userInfoBean;
					}
				} catch (Exception e) {
					e.printStackTrace();
					message.what = -1;
					message.obj = e;
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private void resetViewStatus(boolean flag) {
		if (flag) {
			progressBar.setVisibility(View.GONE);
		} else {
			progressBar.setVisibility(View.VISIBLE);
		}
		registerButton.setClickable(flag);
		head_backImageView.setClickable(flag);
		namEditText.setEnabled(flag);
		lastEditText.setEnabled(flag);
		passwordEditText.setEnabled(flag);
		confirmEditText.setEnabled(flag);
		emailEditText.setEnabled(flag);
		phoneNumberEditText.setEnabled(flag);
		agreeCheckBox.setEnabled(flag);
		sendCheckBox.setEnabled(flag);
	}
}
